﻿using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Ecobee.Net
{
	/// <summary>
	/// 
	/// </summary>
	public class Authorization : SecurityObject
	{
		private string _ecobeePin = string.Empty;
		private Token _authorizationToken = new Token(Token.Kind.Authorization);
		private AuthorizationScope _responseScope = AuthorizationScope.None;
		private int _interval = 0;

		// ***
		// *** Custom properties
		// ***
		private DateTime _timeStamp = DateTime.MinValue;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="responseScope"></param>
		public Authorization(Api api, AuthorizationScope responseScope)
			: base(api)
		{
			this.ResponseScope = responseScope;
		}

		/// <summary>
		/// The PIN a user enters in the web portal.
		/// </summary>
		[JsonProperty(PropertyName = "ecobeePin")]
		public string EcobeePin
		{
			get
			{
				return _ecobeePin;
			}
			set
			{
				_ecobeePin = value;
			}
		}

		/// <summary>
		/// The requested Scope from the original request. This must match the original request.
		/// </summary>
		[JsonProperty(PropertyName = "code")]
		public Token AuthorizationToken
		{
			get
			{
				return _authorizationToken;
			}
			internal set
			{
				_authorizationToken = value;
			}
		}

		/// <summary>
		/// The authorization token needed to request the access and refresh tokens.
		/// </summary>
		[JsonProperty(PropertyName = "scope")]
		public AuthorizationScope ResponseScope
		{
			get
			{
				return _responseScope;
			}
			internal set
			{
				_responseScope = value;
			}
		}

		/// <summary>
		/// The minimum amount of seconds which must pass between polling attempts for a token.
		/// </summary>
		[JsonProperty(PropertyName = "interval")]
		public int Interval
		{
			get
			{
				return _interval;
			}
			internal set
			{
				_interval = value;
			}
		}

		/// <summary>
		/// Makes a request for the a new Authorization with the specified scope.
		/// </summary>
		/// <returns></returns>
		public async Task<bool> GetPinAuthorization()
		{
			bool returnValue = false;

			ApiResult response = await this.Api.Http.Get(this.Api.KnownUri.GetPinAuthorization(this.ResponseScope));

			if (response.Successful)
			{
				this.OnLoadFrom(response.DataObject);
				returnValue = true;
			}
			else
			{
				response.ThrowException();
			}

			return returnValue;
		}

		protected override void OnLoadFrom(object dataObject)
		{
			this.TimeStamp = DateTime.Now;
			base.OnLoadFrom(dataObject);
		}
	}
}
